<template>
  <div class="app-container">
    <!-- 正常页面  start -->
    <div
      style="
        padding: 10px;
        box-shadow: 3px 3px 3px 1px #ddd;
        margin-bottom: 20px;
      "
    >
      <!--工具栏-->
      <div class="head-container">
        <!-- 搜索栏 -->
        <div style="display: flex; justify-content: left">
          <el-input
            v-model="searchList.battery_id"
            placeholder="请输入电池编号"
            style="width: 250px; margin-right: 20px"
            size="small"
            :clearable="true"
            @keyup.enter.native="searchFn"
          />
          <el-select
            v-if="userName !== 'operation'"
            v-model="searchList.id"
            :clearable="true"
            placeholder="请选择站点"
            style="width: 250px; margin-right: 20px"
            size="small"
            multiple
            @keyup.enter.native="searchFn"
          >
            <el-option
              v-for="item in agentIdArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>

          <!--搜索与重置-->
          <div>
            <el-button
              class="filter-item"
              size="mini"
              type="success"
              icon="el-icon-search"
              @click="searchFn"
              >搜索</el-button
            >
            <el-button
              class="filter-item"
              size="mini"
              type="warning"
              icon="el-icon-refresh-left"
              @click="resetFn"
              >重置</el-button
            >
            <!-- <el-button
              size="mini"
              type="primary"
              style="color: #fff"
              @click="testFn"
              >测试</el-button
            > -->
          </div>
        </div>
      </div>
      <!-- 批量解除电池编号---电池全部重启 -->
      <div style="margin-bottom: 10px" v-if="userName !== 'operation'">
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="AddBatteryFn"
        >
          商户添加电池
        </el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="AddBatteryFn1"
        >
          批量导入商户电池
        </el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="danger"
          @click="deleteAllocationBatteryssFn"
        >
          批量解除电池
        </el-button>
        <!-- <el-button
          class="filter-item"
          size="mini"
          type="danger"
          @click="restartAll"
        >
          电池全部重启
        </el-button> -->
      </div>

      <!--Form解除电池表单-->
      <el-dialog
        :visible.sync="isDeleteBattery"
        :title="deleteBatteryTitle"
        width="450px"
      >
        <el-form
          ref="deleteBatteryForm"
          :inline="false"
          :model="deleteBatteryList"
          :rules="deleteBatteryRules"
          size="medium"
          label-width="100px"
        >
          <el-form-item
            label="电池编号"
            label-width="110px"
            prop="batteries_ids"
          >
            <el-input
              placeholder="请输入电池编号,如有多个，请用逗号'，'隔开"
              v-model="deleteBatteryList.batteries_ids"
              type="textarea"
              :clearable="true"
              :autosize="true"
              style="width: 260px"
              :disabled="deleteDisabled"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isDeleteBattery = false" type="text"
            >取消</el-button
          >
          <el-button
            :loading="deleteBatteryLoading"
            type="primary"
            @click="deleteBatteryFn('deleteBatteryForm')"
            >确认</el-button
          >
        </div>
      </el-dialog>

      <!--表格渲染-->
      <el-table
        ref="doLayout"
        :data="list"
        :header-cell-style="{ 'text-align': 'center', color: '#000' }"
        :cell-style="{ 'text-align': 'center' }"
        :highlight-current-row="true"
        :border="true"
        style="width: 100%"
        height="620"
      >
        <el-table-column
          :show-overflow-tooltip="false"
          prop="id"
          min-width="230"
          label="电池编号"
        >
          <template slot-scope="scope">
            <div
              @click="ismaplngFn(scope.row)"
              style="color: rgb(21, 21, 241); cursor: pointer"
              class="tooltip"
            >
              {{ scope.row.id ? scope.row.id : "" }}

              <span class="tooltiptext">点击查看电池定位</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="gms_signal"
          label="gms信号强度"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="mileage"
          label="行驶公里(km)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="v"
          label="总电压(V)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="i"
          label="总电流(A)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="soc"
          label="电量(%)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="ah"
          label="容量(AH)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="pcb_t"
          label="pcb板温度(℃)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="cell_t"
          label="电芯温度(℃)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="shell_t"
          label="外壳温度(℃)"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="loop_sum"
          label="电池循环次数"
        />
        <el-table-column prop="status" label="电池状态">
          <template slot-scope="scope">
            {{
              scope.row.status == 0
                ? "移动"
                : scope.row.status == 1
                ? "静止"
                : scope.row.status == 2
                ? "存储"
                : scope.row.status == 3
                ? "休眠"
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" align="center">
          <template slot-scope="scope">
            <div @click="caozuoChangeFn(scope.row)">
              <el-dropdown trigger="click" @command="caozuoChange">
                <span
                  class="el-dropdown-link"
                  :class="scope.row.id == caozuolist.id ? 'blue' : ''"
                >
                  {{ scope.row.id == caozuolist.id ? caozuolable : "操作" }}
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="a">详情</el-dropdown-item>
                  <el-dropdown-item command="b">解除电池</el-dropdown-item>
                  <el-dropdown-item command="c">重启DTU</el-dropdown-item>
                  <el-dropdown-item command="d">重启MBS</el-dropdown-item>
                  <el-dropdown-item command="e">关闭C/D FET</el-dropdown-item>
                  <el-dropdown-item command="f">关闭C FET</el-dropdown-item>
                  <el-dropdown-item command="g">关闭D FET</el-dropdown-item>
                  <el-dropdown-item command="h">开启C/D FET</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>

            <!-- <el-button
              size="mini"
              type="primary"
              style="color: #fff"
              @click="compileFn(scope.row)"
              >详情</el-button
            >
            <el-button
              size="mini"
              type="danger"
              style="color: #fff"
              @click="deleteAllocationBatteryFn(scope.row)"
              >解除电池</el-button
            >
            <el-button
              size="mini"
              type="danger"
              style="color: #fff"
              @click="deleteAllocationBatteryFn(scope.row)"
              >重启DTU</el-button
            >
            <el-button
              size="mini"
              type="danger"
              style="color: #fff"
              @click="deleteAllocationBatteryFn(scope.row)"
              >重启MBS</el-button
            >
            <el-button
              size="mini"
              type="danger"
              style="color: #fff"
              @click="deleteAllocationBatteryFn(scope.row)"
              >关闭C/D FET</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :page-size.sync="page.size"
        :page-sizes="[5, 10, 20, 30, 50]"
        :total="page.total"
        :current-page.sync="page.page"
        style="margin-top: 8px; text-align: center"
        layout="total,sizes, prev, pager, next, jumper"
        @size-change="sizeChangeFn"
        @current-change="currentChangeFn"
      />
    </div>
    <!-- 正常页面  end -->
    <!-- 地图 -->
    <el-dialog :visible.sync="ismaplng" width="80%">
      <div style="height: 600px; display: flex; justify-content: space-between">
        <baidu-map
          style="width: 100%; height: 600px"
          class="map-wrap"
          :center="mapData.center"
          :zoom="mapData.zoom"
          @ready="mapHandler"
          @click="getLocation"
        >
        </baidu-map>
        <div
          style="width: 300px; padding: 10px; box-shadow: 3px 3px 3px 1px #ddd"
        >
          <div style="padding: 10px; box-shadow: 3px 3px 3px 1px #ddd">
            <!-- <div class="textling">
              <span style="padding-right: 10px"
                >总电池：{{ list.length || 0 }}个</span
              >
              已定位电池：{{ addressBatteryNumber || 0 }}个
            </div> -->
            <div class="textling">电池编号：{{ ismaplngList.id || "--" }}</div>
            <div class="textling">电池电压：{{ ismaplngList.v || "--" }}</div>
            <div class="textling">电池电流：{{ ismaplngList.i || "--" }}</div>
            <div class="textling">电池电量：{{ ismaplngList.soc || "--" }}</div>
            <div class="textling">
              gms信号强度：{{ ismaplngList.gms_signal || "--" }}
            </div>
            <div class="textling">
              行驶公里(km)：{{ ismaplngList.mileage || "--" }}
            </div>

            <div class="textling">
              状态：{{
                ismaplngList.status == 0
                  ? "移动"
                  : ismaplngList.status == 1
                  ? "静止"
                  : ismaplngList.status == 2
                  ? "存储"
                  : ismaplngList.status == 3
                  ? "休眠"
                  : "--"
              }}
            </div>
            <div>
              <el-button
                type="success"
                size="mini"
                :plain="true"
                style="width: 100%"
                @click="compileFns"
                >详情</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 重启 -->
    <el-popover
      v-model="caozuorestart"
      placement="top"
      width="200"
      style="position: fixed; right: 48%; top: 12%"
    >
      <p>
        {{
          restartNum == 0
            ? "确定让该电池 重启DTU ？"
            : restartNum == 1
            ? "确定让该电池 重启MBS ？"
            : restartNum == 2
            ? "确定 全部重启 电池 ？"
            : "重启 电池"
        }}
      </p>
      <div style="text-align: right; margin: 0">
        <el-button size="mini" type="text" @click="caozuorestart = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="quedingrestartFn"
          >确定</el-button
        >
      </div>
    </el-popover>

    <!-- 电池 控制 FET -->
    <el-popover
      v-model="caozuoFET"
      placement="top"
      width="200"
      style="position: fixed; right: 48%; top: 12%"
    >
      <p>
        {{
          FETNum == 0
            ? "确定让该电池 关闭C/D FET ？"
            : FETNum == 1
            ? "确定让该电池 关闭C FET ？"
            : FETNum == 2
            ? "确定 全部重启 关闭D FET ？"
            : FETNum == 3
            ? "确定 全部重启 开启C/D FET ？"
            : "控制 电池 FET"
        }}
      </p>
      <div style="text-align: right; margin: 0">
        <el-button size="mini" type="text" @click="caozuoFET = false"
          >取消</el-button
        >
        <el-button type="primary" size="mini" @click="quedingFETFn"
          >确定</el-button
        >
      </div>
    </el-popover>

    <!-- 添加电池模态框 -->
    <el-dialog
      :visible.sync="uploadFile_fag"
      title="给商户添加电池"
      width="500px"
    >
      <el-form
        ref="Mbattery"
        :inline="false"
        :model="MbatteryList"
        :rules="MbatteryRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="添加电池" prop="battery_id">
          <el-input
            v-model="MbatteryList.battery_id"
            placeholder="请输入电池编号,如有多个，请用逗号'，'隔开"
            type="textarea"
            :clearable="true"
            style="width: 260px"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadFile_fag = false" type="text">取消</el-button>
        <el-button type="primary" @click="MbatteryConfirmFn('Mbattery')"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!-- 批量--添加电池模态框 -->
    <el-dialog
      title="批量导入商户电池"
      :visible.sync="uploadFile_fag1"
      width="30%"
    >
      <div class="content" style="text-align: center">
        <el-upload
          class="upload-demo"
          ref="uploadBattery"
          action="#"
          :show-file-list="true"
          :limit="1"
          :on-exceed="handleExceed"
          :http-request="httpRequest"
        >
          <div style="display: flex; justify-content: center">
            <el-button
              style="margin-right: 30px"
              slot="trigger"
              size="small"
              type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传 xlsx 和 xls 格式
            </div>
          </div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { urlObj, comurlObj } from "@/api/login";
import DistanceTool from "bmaplib.distancetool";
import axios from "axios";
export default {
  data() {
    return {
      // 控制添加电池模态框   start
      uploadFile_fag1: false, //控制添加电池模态框的显示隐藏
      fileList: [],

      uploadFile_fag: false,
      MbatteryList: {},
      MbatteryRules: {
        battery_id: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      // 控制添加电池模态框  end

      // 操作下拉框  strat
      caozuolist: {},
      caozuolable: "操作",
      caozuorestart: false,
      restartNum: null,
      caozuoFET: false,
      FETNum: null,
      // 操作下拉框  end
      searchList: {
        id: "",
        battery_id: "",
      }, // 搜索数据
      list: [], //列表数据
      page: {
        size: 10, //每页的数量
        page: 1, //当前页
        total: 0, //总数
      }, //分页
      userName: "", //获取角色名称
      agentIdArr: [], //站点列表
      //地图数据
      mapData: {
        //中心坐标
        center: { lng: null, lat: null },
        //缩放级别
        zoom: 15,
      },
      //BMap类
      BMap: null,
      //地图对象
      map: null,
      distanceTool: null,
      businessDetail: "",
      checkedObj: {},
      addressBatteryNumber: 0, //已有定位的电池
      ismaplng: false,
      ismaplngList: {},
      // 解除电池
      isDeleteBattery: false,
      deleteBatteryTitle: "解除电池", //解除电池表单标题
      deleteBatteryLoading: false, //解除电池确认状态--加载与否
      deleteBatteryList: {
        //解除电池表单数据
        batteries_ids: "",
        merchant_id: "",
      },
      deleteBatteryRules: {
        //解除电池表单规则
        batteries_ids: [
          { required: true, message: "请输入电池", trigger: "change" },
        ],
      },
      deleteDisabled: false,
    };
  },
  mounted() {
    this.userName =
      JSON.parse(sessionStorage.getItem("userObj")).user_type || "";
    this.listFn();
    this.stationFn();
    let prarms = {
      func: "getNotBindMerchantBattery",
      token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
      business: {},
    };
    urlObj(prarms).then((res) => {
      // console.log(4334234, res);
    });
  },

  methods: {
    // 操作下拉框  strat
    caozuoChange(val) {
      if (val == "a") {
        this.caozuolable = "详情";
        this.compileFn(this.caozuolist);
      }
      if (val == "b") {
        this.caozuolable = "解除电池";
        this.deleteAllocationBatteryFn(this.caozuolist);
      }
      if (val == "c") {
        this.caozuolable = "重启DTU";
        this.caozuorestart = true;
        this.restartNum = 0;
      }
      if (val == "d") {
        this.caozuolable = "重启MBS";
        this.caozuorestart = true;
        this.restartNum = 1;
      }
      if (val == "e") {
        this.caozuolable = "关闭C/D FET";
        this.caozuoFET = true;
        this.FETNum = 0;
      }
      if (val == "f") {
        this.caozuolable = "关闭C FET";
        this.caozuoFET = true;
        this.FETNum = 1;
      }
      if (val == "g") {
        this.caozuolable = "关闭D FET";
        this.caozuoFET = true;
        this.FETNum = 2;
      }
      if (val == "h") {
        this.caozuolable = "开启C/D FET";
        this.caozuoFET = true;
        this.FETNum = 3;
      }
    },
    // 拿到列表一行数据
    caozuoChangeFn(row) {
      this.caozuolist = row || {};
    },

    // 电池 控制 FET--确认按钮
    quedingFETFn() {
      this.caozuoFET = false;
      let prarms = {
        func: "bat_reboot",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          battery_id: this.caozuolist.id,
          control_value: this.FETNum,
        },
      };
      comurlObj(prarms)
        .then((res) => {
          this.listFn();
          this.$message({
            message: res.msg || "",
            type: res.code == 0 ? "success" : "error",
          });
        })
        .catch((error) => {
          this.$message({
            message: res.msg || "",
            type: "error",
          });
        });
    },

    // // 全部重启
    // restartAll() {
    //   this.caozuorestart = true;
    //   this.restartNum = 2;
    // },

    // 重启--确认按钮
    quedingrestartFn() {
      this.caozuorestart = false;
      let prarms = {
        func: "bat_reboot",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          battery_id: this.caozuolist.id,
          reboot_value: this.restartNum,
        },
      };
      comurlObj(prarms)
        .then((res) => {
          this.listFn();
          this.$message({
            message: res.msg || "",
            type: res.code == 0 ? "success" : "error",
          });
        })
        .catch((error) => {
          this.$message({
            message: res.msg || "",
            type: "error",
          });
        });
    },

    // 操作下拉框  end

    // 分页---每页的数量
    sizeChangeFn(val) {
      this.page.size = val;
      this.page.page = 1;
      this.listFn();
    },
    // 当前页数
    currentChangeFn(val) {
      this.page.pege = val;
      this.listFn();
    },
    // 重置
    resetFn() {
      this.searchList.id = "";
      this.searchList.battery_id = "";
      this.listFn();
      this.page.size = 10;
      this.page.page = 1;
    },
    // 搜索
    searchFn() {
      this.page.size = 10;
      this.page.page = 1;

      this.listFn();
    },
    // 列表数据
    listFn() {
      let prarms = {
        func: "getBattery",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          station_id: this.searchList.id || [],
          battery_id: this.searchList.battery_id || "",
        },
        page_no: this.page.page,
        page_size: this.page.size,
      };
      urlObj(prarms).then((res) => {
        this.list = res.result || [];
        this.page.total = res.count || 0;
        if (res.result) {
          this.list.forEach((item) => {
            item.v = item.v ? item.v / 100 : "0";
            item.i = item.i ? item.i / 100 : "0";
            item.ah = item.ah ? item.ah / 100 : "0";
          });
          // this.page.total = res.result.length || 0;
          // 增加临时的
          // this.list.forEach((item, index) => {
          //   this.list[index].lat = 23.12652 + index;
          //   this.list[index].lng = 113.25878 + index;
          // });
        }
      });
    },
    // 站点列表
    stationFn() {
      let prarms = {
        func: "getStation",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
      };
      urlObj(prarms).then((res) => {
        var data = res.result || [];
        this.agentIdArr = [];
        if (data.length !== 0) {
          data.forEach((i) => {
            let testAgentArr = {
              id: i.id,
              name: i.station_name,
            };
            this.agentIdArr.push(testAgentArr);
          });
        }
      });
    },

    // 解除电池按钮
    deleteAllocationBatteryssFn() {
      this.isDeleteBattery = true;
      this.deleteDisabled = false;
      this.deleteBatteryList.batteries_ids = "";
      this.deleteBatteryList.merchant_id =
        JSON.parse(sessionStorage.getItem("userObj")).id || "";
    },

    // 列表解除电池按钮
    deleteAllocationBatteryFn(row) {
      this.isDeleteBattery = true;
      this.deleteDisabled = true;
      this.deleteBatteryList.batteries_ids = row.id || "";
      this.deleteBatteryList.merchant_id =
        JSON.parse(sessionStorage.getItem("userObj")).id || "";
    },
    // 列表解除电池按钮 --确定
    deleteBatteryFn(val) {
      let batteries_ids = this.deleteBatteryList.batteries_ids;
      let batteries_idsList = [];
      if (batteries_ids.includes(",")) {
        batteries_idsList = batteries_ids.split(",");
      } else if (batteries_ids.includes("，")) {
        batteries_idsList = batteries_ids.split("，");
      } else {
        batteries_idsList = [batteries_ids];
      }
      let prarms = {
        func: "batteryUnbindMerchant",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          merchant_id: this.deleteBatteryList.merchant_id,
          batteries_ids: batteries_idsList || [],
        },
      };
      this.$refs[val].validate(async (valid) => {
        if (valid) {
          this.deleteBatteryLoading = true;
          urlObj(prarms)
            .then((res) => {
              this.listFn();
              this.$message({
                message: res.msg || "",
                type: res.code == 0 ? "success" : "error",
              });
            })
            .catch((error) => {
              this.$message({
                message: res.msg || "",
                type: "error",
              });
            });
          this.deleteBatteryLoading = false;
          this.isDeleteBattery = false;
        }
      });
    },

    // 商户添加电池---模态框  start
    // 商户添加电池
    AddBatteryFn() {
      this.uploadFile_fag = true;
    },
    // 商户添加电池---模态框 确认
    MbatteryConfirmFn(val) {
      let batteries_ids = this.MbatteryList.battery_id;
      let batteries_idsList = [];
      if (batteries_ids.includes(",")) {
        batteries_idsList = batteries_ids.split(",");
      } else if (batteries_ids.includes("，")) {
        batteries_idsList = batteries_ids.split("，");
      } else {
        batteries_idsList = [batteries_ids];
      }

      let prarms = {
        func: "setBatteryMerchant",
        token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
        business: {
          battery_id: batteries_idsList || [], //电池编号
          excel_file: "", //excel文件
        },
      };

      this.$refs[val].validate(async (valid) => {
        if (valid) {
          urlObj(prarms)
            .then((res) => {
              this.listFn();
              this.$message({
                message: res.msg || "",
                type: res.code == 0 ? "success" : "error",
              });
            })
            .catch((error) => {
              this.$message({
                message: res.msg || "",
                type: "error",
              });
            });
          this.uploadFile_fag = false;
          this.MbatteryList.battery_id = "";
        }
      });
    },

    AddBatteryFn1() {
      this.uploadFile_fag1 = true;
    },
    //这个file参数 也就是文件信息，你使用 插件 时 你就可以打印出文件信息 看看嘛
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file); //开始转
        reader.onload = function () {
          fileResult = reader.result;
        }; //转 失败
        reader.onerror = function (error) {
          reject(error);
        }; //转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
    //文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      // console.log('文件超出个数限制时的钩子', file, fileList);
      this.$message({
        message: "只能上传一个文件",
        type: "error",
      });
    },
    httpRequest(data) {
      // 没事儿就打印data看看呗　　　　//这是限制上传文件类型
      console.log(333, data);
      const isPFX =
        data.file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isLt2M = data.file.size / 1024 / 1024 < 2;

      // if (!isPFX) {
      //   this.$message.error("上传文件只能是 XLSX 格式!");
      // } else
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
      } else {
        // 转base64
        this.getBase64(data.file).then((resBase64) => {
          // console.log(resBase64.split(",")[1]); //直接拿到base64信息
          let prarms = {
            func: "setBatteryMerchant",
            token: JSON.parse(sessionStorage.getItem("userObj")).token || "",
            business: {
              battery_id: [], //电池编号
              excel_file: resBase64.split(",")[1] || "", //excel文件
            },
          };
          urlObj(prarms)
            .then((res) => {
              this.listFn();
              this.$message({
                message: res.msg || "",
                type: res.code == 0 ? "success" : "error",
              });
            })
            .catch((error) => {
              this.$message({
                message: res.msg || "",
                type: "error",
              });
            });
          this.uploadFile_fag1 = false;
        });
      }
    },
    // 商户添加电池---模态框  end

    // 电池详情 start
    // 详情
    compileFn(row) {
      console.log(3434, row.lat);
      if (row.lat && row.lng) {
        let _self = this;
        axios
          .get(
            ` https://api.map.baidu.com/geoconv/v1/?coords=${row.lng},${row.lat}&from=1&to=5&ak=uQ1kN7e2ILDy4w5LGQ4c14uEd7KK2GGY`
          )
          .then((res) => {
            // console.log("成功", res.data.result[0]);
            row.lng = res.data.result[0].x;
            row.lat = res.data.result[0].y;
            _self.$router.push({
              path: "/merchantManagement/merchantBattery/details",
              query: { row: JSON.stringify(row) },
            });
          });
      } else {
        this.$router.push({
          path: "/merchantManagement/merchantBattery/details",
          query: { row: JSON.stringify(row) },
        });
      }
    },
    testFn() {
      // this.$router.push({
      //   path: "/homeLogo",
      // });
      this.$router.push({
        path: "/merchantManagement/merchantBattery/test",
      });
    },

    // 电池详情 end
    // 地图详情
    compileFns() {
      this.$router.push({
        path: "/merchantManagement/merchantBattery/details",
        query: { row: JSON.stringify(this.checkedObj) },
      });
    },

    // 地图
    // 打开测距功能
    openDistanceTool(e) {
      const { distanceTool } = this;
      distanceTool && distanceTool.open();
    },
    destroyed() {
      //销毁
      this.distanceTool.close();
    },

    // 点击设备编号出现地图
    ismaplngFn(row) {
      if (row.lng && row.lat) {
        this.ismaplng = true;
        this.ismaplngList = row || {};
        console.log(1111111, row);
      } else {
        this.$message({
          message: "该电池没有经纬度信息",
          type: "error",
        });
      }
    },

    //地图预处理
    async mapHandler({ BMap, map }) {
      setTimeout(async () => {
        //保存百度地图类
        this.BMap = BMap;
        //保存地图对象
        this.map = map;

        // 测距功能
        this.distanceTool = new DistanceTool(map, { lineStroke: 2 });

        //监听测距尺关闭的时候触发
        this.distanceTool.addEventListener("removepolyline", function (e) {
          // console.log("测距尺关闭", e);
        });
        //监听测距尺鼠标点击添加点的时候触发
        this.distanceTool.addEventListener("addpoint", function (e) {
          // console.log(
          //   "测距尺点击添加点",
          //   e.point,
          //   e.pixel,
          //   e.index,
          //   e.distance,
          //   e
          // );
        });
        //监听测距尺鼠标右击测距尺添加完成的时候触发
        this.distanceTool.addEventListener("drawend", function (e) {
          //点数组
          // console.log("测距尺添加完成", e.points, e.overlays, e.distance, e);
        });

        // 按住鼠标右键，修改倾斜角和角度
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        // map.setHeading(64.5);   //设置地图旋转角度
        // map.setTilt(73);       //设置地图的倾斜角度
        //设置坐标

        //创建定位标记
        if (this.list.length !== 0) {
          // 刷选有经纬度的电池列表
          var batteryList = [this.ismaplngList];
          // var batteryList = this.list.filter(
          //   (item) => item.lat && item.lng && item.lat !== 0 && item.lng !== 0
          // );
          // 把电池列表的wcs-84经纬度转化为百度经纬度
          batteryList.forEach((item, index) => {
            // 坐标转换
            axios
              .get(
                ` https://api.map.baidu.com/geoconv/v1/?coords=${item.lng},${item.lat}&from=1&to=5&ak=uQ1kN7e2ILDy4w5LGQ4c14uEd7KK2GGY`
              )
              .then((res) => {
                // console.log("成功", res.data.result[0]);
                item.lng = res.data.result[0].x;
                item.lat = res.data.result[0].y;
              });
          });
          setTimeout(async () => {
            let firstGreaterThanTen = batteryList.find(function (item) {
              return item.lat && item.lng;
            });
            this.checkedObj = firstGreaterThanTen;
            // 将地图中心移到最新一个电池上
            this.mapData.center.lng = batteryList[0].lng;
            this.mapData.center.lat = batteryList[0].lat;
            // this.mapData.center.lng = this.checkedObj.lng;
            // this.mapData.center.lat = this.checkedObj.lat;
            batteryList.forEach((item) => {
              if (item.lat && item.lng) {
                this.addressBatteryNumber = this.addressBatteryNumber + 1;
              }
            });
            // 根据电池列表，在地图上添加标记
            batteryList.forEach((item, index) => {
              // 自定义地图图标与尺寸
              var imgUrl = require("../../../assets/images/latlng.png");
              var redimgUrl = require("../../../assets/images/redlatlng.png");
              const icon = new BMap.Icon(imgUrl, new BMap.Size(32, 32));

              // console.log("现在的", item.lng, item.lat);
              // 设置标记点经纬度
              let point = new BMap.Point(item.lng, item.lat);
              //将设置好的图标、尺寸、经纬度标记添加到地图上
              let marker = new BMap.Marker(point, {
                icon: icon,
              });
              map.addOverlay(marker);
              // 添加标记的气泡窗口
              marker.setLabel(
                new BMap.Label("电池" + item.id, {
                  offset: new BMap.Size(15, -25),
                })
              );

              //给小图标加参数并加点击事件
              (() => {
                //给每一个小图标加点击事件
                let data = {
                  id: item.id,
                  v: item.v,
                  i: item.i,
                  soc: item.soc,
                  gms_signal: item.gms_signal,
                  mileage: item.mileage,
                  status: item.status,
                  imsi: item.imsi,
                  battery_status: item.battery_status,
                  hard_version: item.hard_version,
                  soft_version: item.soft_version,
                  protocol_version: item.protocol_version,
                  socket_index: item.socket_index,
                  loc_type: item.loc_type,
                  lng: item.lng,
                  lat: item.lat,
                  gms: item.gms,
                  speed: item.speed,
                  ah: item.ah,
                  cell_sum: item.cell_sum,
                  cells_v: item.cells_v,
                  pcb_t: item.pcb_t,
                  cell_t: item.cell_t,
                  shell_t: item.shell_t,
                  loop_sum: item.loop_sum,
                  mer_id: item.mer_id,
                  station_id: item.station_id,
                };
                //定义this指向
                let that = this;
                marker.addEventListener("click", function () {
                  that.checkedObj = data;
                });
                // 标记气泡  strat
                //   var steelContent = `<div>
                //      <div style="margin-top: 5px">电池编号:${data.id}</div>
                // </div>`;
                //   var steelOpts = {
                //     width: 250, //信息窗口宽度
                //     height: 120, //信息窗口高度
                //     enableMessage: true, //设置允许信息窗发送短息
                //   };

                //   marker.addEventListener("mouseover", function () {
                //     this.openInfoWindow(
                //       new BMap.InfoWindow(steelContent, steelOpts)
                //     );
                //   });
                //   //添加鼠标离开时关闭自定义信息窗口事件
                //   marker.addEventListener("mouseout", function () {
                //     this.closeInfoWindow();
                //   });
                // 标记气泡  end
              })();
            });
          }, 500);
        } else {
          this.checkedObj = {};
        }
      }, 1500);
    },

    //点击地图
    getLocation(e) {
      // 测距
      this.openDistanceTool();

      // console.log(44444, e.point, e);
      // // this.mapData.zoom = 20;
      // //设置经度
      // this.mapData.center.lng = e.point.lng;
      // //设置纬度
      // this.mapData.center.lat = e.point.lat;
      // //百度地图类
      // let BMapGL = this.BMap;
      // let geoc = new BMapGL.Geocoder();
      // //解析当前的坐标成地址
      // geoc.getLocation(e.point, (rs) => {
      //   console.log(1212, e.point, rs);
      //   //获取地址对象
      //   let addressComp = rs.addressComponents;
      //   //拼接出详细地址
      //   this.businessDetail =
      //     addressComp.province +
      //     addressComp.city +
      //     addressComp.district +
      //     addressComp.street +
      //     addressComp.streetNumber;
      //   console.log(66, this.businessDetail);
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.textling {
  font-size: 13px;
  line-height: 35px;
}
.blue {
  color: rgb(50, 62, 231);
  font-weight: 700;
}
.tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  bottom: -50%;
  left: 50%;
  margin-left: -60px;
}

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 0%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: black transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
</style>
